/*
 * SaveLoadUtils.java
 *
 * Created on 11.12.2007, 18:35:36
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.possoft.client.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cz.possoft.serializable.generic.Game;


/**
 *
 * @author mara
 *
 * trida slouzi k ukladani her a nacitani.
 */
public class SaveLoadUtils {

    public SaveLoadUtils() {
    }

    // slouzi k ulozeni hry do souboru do adresare games
    // vraci 0 - uspesne ulozeni hry
    //       1 - ioexception
    //       2 - jmeno jiz existuje
    public static int writeGame(Game game, String gameName, String userName) {
        ObjectOutputStream out = null;
        try {
            // podtrzitka v nazvu hrace i souboru nahradim pomlckama
            gameName = gameName.replace('_', '-');
            userName = userName.replace('_', '-');
            String fileName = "games/" + gameName + "_" + userName + ".svg";
            if (!controlFileName(fileName)) {
                return 2;
            }
            out = new ObjectOutputStream(new FileOutputStream(fileName));
            out.writeObject(game);
            out.flush();
            return 0;
        } catch (IOException io) {
            System.err.println("System err. exception ");
            io.printStackTrace();
            return 1;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException exception) {
                    System.err.println("System err. exception ");
                    exception.printStackTrace();
                    return 1;
                }
            }
        }
    }

    // vraci seznam nazvu souboru z adresare games
    public static String[] getSavedGames() {
        File gameAdr = new File("games");
        try {
            String[] p = gameAdr.list();
            return p;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // smaze vybranou hru. Vstupni pole obsahuje cely HTML kod z listu, takze je jeste treba ho zpracovat
    // vraci true pokud smazani probehlo uspesne.
    public static boolean deleteSavedGame(String gameForDelete) {
        try {
            gameForDelete = transformToFileName(gameForDelete);
            File f = new File(gameForDelete);
            return f.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // z vybraneho nazvu hry z listu vybere soubor s hrou a z nej vraci tuto hru
    public static Game loadGame(String selected) {
        String fileName = transformToFileName(selected);

        ObjectInputStream in = null;

        try {
            in = new ObjectInputStream(new FileInputStream(fileName));
            Object o = in.readObject();
            return (Game) o;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
    }

    // z jmena usera v html textu mezi tagy <i> a </i> vyparsuje jmeno usera
    private static String getUserNameFromHtml(String labelText) {
        int i1 = labelText.indexOf("<I>");
        int i2 = labelText.indexOf("</I>");
        if ((i1 != -1) && (i2 != -1)) {
            return labelText.substring(i1 + 3, i2);
        } else {
            return "";
        }
    }

    // z jmena souboru z listu obsahujici HTML a neobsahujici priponu vyparsuje jmeno oponenta
    public static String getUserNameFromListValue(String nameFromList) {
        int i1 = nameFromList.indexOf("red>");
        int i2 = nameFromList.indexOf("</FONT>");
        if ((i1 != -1) && (i2 != -1)) {
            String fullName = nameFromList.substring(i1 + 4, i2);
            int i3 = fullName.indexOf("_");
            if (i3 != -1) {
                return fullName.substring(i3 + 1);
            }
        }
        return "";
    }

    // z jmena souboru z listu obsahujici HTML a neobsahujici priponu vyparsuje jmeno souboru
    // a prida prefix i priponu games/
    private static String transformToFileName(String nameFromList) {
        int i1 = nameFromList.indexOf("red>");
        int i2 = nameFromList.indexOf("</FONT>");
        if ((i1 != -1) && (i2 != -1)) {
            return "games/" + nameFromList.substring(i1 + 4, i2) + ".svg";
        } else {
            return "";
        }
    }

    // zjisti jestli jmeno souboru neni obsazeno v jiz ulozenych hrach. Pokud ano, vraci false.
    private static boolean controlFileName(String fileName) {
        String[] p = getSavedGames();
        for (int i=0; i<p.length ; i++) {
            String s = p[i];
            if (fileName.equals("games/" + s)) {
                return false;
            }
        }
        return true;
    }

    // ze souboru server.txt vyparsuje jmeno hosta, ke kteremu se bude klient pripojovat
    public static String returnHostName() {
    	BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("server.txt"));
            String s = br.readLine();            
            return s;
        } 
        catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
        finally {   
        	try {
             	br.close();
        	}
        	catch (IOException ioe) {
        	    ioe.printStackTrace();	
        	}        	
        }
    }
}
